package com.eascs.web.p2p.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.app.dao.PageResult;
import com.eascs.common.util.DateUtils;
import com.eascs.p2p.common.constants.SendType;
import com.eascs.p2p.common.dto.MessageDTO;
import com.eascs.p2p.common.dto.MessageReceiver;
import com.eascs.p2p.common.entity.InvestObjectEntity;
import com.eascs.p2p.common.entity.InvestorRecordEntity;
import com.eascs.p2p.common.entity.LoaneeEntity;
import com.eascs.p2p.common.entity.LoaneeRefundPlanEntity;
import com.eascs.p2p.common.service.IInvestObjectService;
import com.eascs.p2p.common.service.IInvestorRecordService;
import com.eascs.p2p.common.service.ILoaneeRefundPlanService;
import com.eascs.p2p.common.service.ILoaneeService;
import com.eascs.p2p.common.service.IMessageService;
import com.eascs.p2p.common.service.InvestorIncomeDetailService;
import com.eascs.p2p.common.service.InvestorService;
import com.eascs.p2p.common.vo.LoaneeRefundPlanVO;
import com.eascs.p2p.common.vo.ModelResult;
import com.eascs.p2p.common.vo.RepaymentVO;
import com.eascs.p2p.common.wallet.service.InvestorWalletService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ShowButtonFilter;

@Controller
@RequestMapping("/refundRest")
public class LoaneeRefundPlanRestController extends BaseRestController {

	@Reference
	ILoaneeRefundPlanService loaneeRefundPlanService;
	@Reference
	IInvestObjectService investObjectService;
	@Reference
	ILoaneeService loaneeService;
	@Reference
	IMessageService messageService;
	@Reference
	InvestorWalletService investorWalletService;
	@Reference
	InvestorService investorService;
	@Reference
	InvestorIncomeDetailService investorIncomeDetailService;

	@RequestMapping(value = "/plan")
	public HtmlRestResult plan(LoaneeRefundPlanVO vo) {
		LoaneeRefundPlanEntity plan = null;
		ModelResult<LoaneeRefundPlanEntity> plan_model = loaneeRefundPlanService.findLoaneeRefundPlanById(vo.getId());
		if (plan_model.isSuccess()) {
			plan = plan_model.getModel();
		}

		vo.setBidId(plan.getObjectId());
		vo.setPageSize(10);
		ModelResult<PageResult<Object[]>> model = loaneeRefundPlanService.findAllPageLoaneeRefundPlanEntity(vo);
		PageResult<Object[]> pageResult = new PageResult<Object[]>();
		if (model.isSuccess()) {
			pageResult = model.getModel();
		}

		String[] titles = { "其次", "应还款日期", "实际还款日期", "应还总额", "应还本金", " 应还利息  ", "是否逾期 ", "还款状态" };

		AjaxButton refundButton = new AjaxButton("  还款", "/refundRest/refund?id=");
		refundButton.setShowButtonFilter(new ShowButtonFilter() {

			@Override
			public boolean filter(Object param) {
				Object[] params = (Object[]) param;
				return (!"已还款".equals(params[7]));
			}
		});

		Button[] buttons = new Button[] { refundButton };

		String findCondition = "";
		String pageUrl = "/refundRest/plan";

		if (vo != null) {
			String title = vo.getTitle() == null ? "" : vo.getTitle();

			findCondition = "?title=" + title;

			pageUrl = pageUrl + findCondition;
		}
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, pageUrl + "&showPage=");
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(0);
		paginationInfo.setMoreButtons(buttons);
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("vo", vo);
		ModelResult<InvestObjectEntity> recordModel = investObjectService.findInvestObjectDetail(vo.getBidId());
		InvestObjectEntity object = new InvestObjectEntity();
		if (recordModel.isSuccess()) {

			object = recordModel.getModel();
		}
		ViewContext.put("object", object);

		if (object != null) {

			ModelResult<LoaneeEntity> loaneeModel = loaneeService.findLoaneeEntityDetail(object.getLoaneeId());
			LoaneeEntity loanee = new LoaneeEntity();
			if (loaneeModel.isSuccess()) {

				loanee = loaneeModel.getModel();
			}
			ViewContext.put("loanee", loanee);
		}
		BaseRestResult.refresh();
		return HtmlRestResult.popHtmlFragment("/refund/plan");

	}

	@RequestMapping(value = "/warn")
	public BaseRestResult<String> warn(String id) {
		LoaneeRefundPlanEntity plan = null;
		ModelResult<LoaneeRefundPlanEntity> plan_model = loaneeRefundPlanService.findLoaneeRefundPlanById(id);
		if (plan_model.isSuccess()) {
			plan = plan_model.getModel();
		}

		ModelResult<LoaneeEntity> loaneeModel = loaneeService.findLoaneeEntityDetail(plan.getLoanee());
		LoaneeEntity loanee = new LoaneeEntity();
		if (loaneeModel.isSuccess()) {

			loanee = loaneeModel.getModel();
		}
		BaseRestResult<String> result = null;
		MessageDTO vo = new MessageDTO();
		String msgContent = "您的借款快到期了，请及时还款";
		vo.setMsgContent(msgContent);
		vo.setSenderName("longlong.wang");
		vo.setSendType(SendType.NOW);
		List<MessageReceiver> list = new ArrayList<MessageReceiver>();
		MessageReceiver receiver = new MessageReceiver();
		receiver.setName(loanee.getName());
		receiver.setPhone(loanee.getMobile());
		list.add(receiver);
		vo.setReceivers(list);
		ModelResult<Boolean> flag = messageService.sendMsg(vo);
		if (flag.isSuccess()) {
			if (flag.getModel()) {
				result = BaseRestResult.warn("催款成功").andRedirect("/loaner/index");

			} else {
				result = BaseRestResult.error("催款失败");
			}

		} else {

			result = BaseRestResult.error("催款失败,短信借款发生异常");
		}
		return result;

	}

	/**
	 * @Title: backMoney
	 * @Description: 还款
	 * @author 张庆奇
	 * @param id
	 * @return
	 * @return BaseRestResult<String>
	 * @throws @date
	 *             2016年8月8日 下午5:19:15
	 */
	@RequestMapping(value = "/refund")
	public BaseRestResult<String> refund(String id) {
		BaseRestResult<String> result = null;
		LoaneeRefundPlanEntity plan = null;
		int status = 0;
		boolean flag = false;
		ModelResult<LoaneeRefundPlanEntity> model = loaneeRefundPlanService.findLoaneeRefundPlanById(id);
		// ModelResult<InvestObjectEntity> model =
		// investObjectService.findInvestObjectDetail(id);
		if (model.isSuccess()) {
			plan = model.getModel();
		}

		String str1 = DateUtils.formateStandTime(new Date());// 实际还款日期
		System.out.println("str1: " + str1);
		String str2 = DateUtils.formateStandTime(plan.getMustRefundTime());// 应该还款日期
		System.out.println("str2: " + str2);

		int result_date = str1.compareTo(str2);
		// 还款逾期
		if (result_date > 0) {
			status = 1;
		}
		List<RepaymentVO> repayments = new ArrayList<RepaymentVO>();
		ModelResult<List<RepaymentVO>> modelRepayment = investorIncomeDetailService
				.getInvestorIncome(plan.getObjectId(), plan.getIssue());
		if (modelRepayment.isSuccess()) {
			repayments = modelRepayment.getModel();
		}

		// 1.调用还款接口
		ModelResult<Boolean> returnFlag = investorWalletService.repaymentWalletHandle(repayments);

		if (returnFlag.isSuccess()) {
			flag = returnFlag.getModel();
		}
		if (flag) {
			ModelResult<Boolean> flag_model = loaneeRefundPlanService.refundMoney(id, status);
			if (flag_model.isSuccess()) {
				flag = flag_model.getModel();
			}
		}

		if (flag) {
			result = BaseRestResult.warn("还款成功").andRefresh();
		} else {
			result = BaseRestResult.error("还款失败");
		}
		return result;

	}

}
